package com.wonders.frame.chron.service;



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wonders.frame.chron.config.ChronConfig;

/**
 * 调用流程接口
 * Created by 01053953 on 2016/8/1.
 */
@Service
public class WebUtilService {
    @Autowired
    private ChronConfig chronConfig;

    /**
     * 获取流程轨迹
     * @param procInsId 流程ID
     * @return
     * @throws Exception
     */
    public List<Map<String,String>> getComments(String procInsId) throws Exception {
        String soapRequestData=
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:getComments>\n" +
                        "         <arg0>"+procInsId+"</arg0>\n" +
                        "      </web:getComments>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("getComments调用成功！");
            String soapResponseData = postMethod.getResponseBodyAsString().replace("&lt;", "<").replace("&gt;",">");
            soapResponseData  = soapResponseData.split("return")[1];
            soapResponseData= soapResponseData.substring(1,soapResponseData.length());
            soapResponseData= soapResponseData.substring(0,soapResponseData.length()-2);
            //System.out.println("soapResponseData = " + soapResponseData);
            if(!soapResponseData.contains("completeMessage")){
                return null;
            }else{
                Document doc = DocumentHelper.parseText(soapResponseData.trim());
                Element root = doc.getRootElement();
                //System.out.println("soapResponseData = " + soapResponseData);
                return getNodes(root);
            }
        }
        else {
            System.out.println("getComments调用失败！错误码：" + statusCode);
            return null;
        }
    }

    /**
     * 获取流程图信息
     * @param procInsId 流程ID
     * @return
     * @throws Exception
     */
    public String getProcessDefinitionId(String procInsId) throws Exception {
        String soapRequestData=
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:getProcessDefinitionId>\n" +
                        "         <!--Optional:-->\n" +
                        "         <arg0>"+procInsId+"</arg0>\n" +
                        "      </web:getProcessDefinitionId>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("getProcessDefinitionId调用成功！");
            String soapResponseData = postMethod.getResponseBodyAsString();
            soapResponseData = soapResponseData.split("return")[1].replace(">","").replace("</","");
//            Map<String,String> paramMap = new HashMap<String, String>();
            if(!soapResponseData.contains("end")){
                return soapResponseData;
            }else{
                return null;
            }
        }
        else {
            System.out.println("getProcessDefinitionId调用失败！错误码：" + statusCode);
            return null;
        }
    }
    
    /**
     * 获取当前流程
     * @param procInsId	流程ID
     * @return
     * @throws Exception
     */
    public Map<String,String> getStatus(String procInsId) throws Exception {
        String soapRequestData=
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:getStatu>\n" +
                        "         <!--Optional:-->\n" +
                        "         <arg0>"+procInsId+"</arg0>\n" +
                        "      </web:getStatu>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("getStatus调用成功！");
            String soapResponseData = postMethod.getResponseBodyAsString();
            soapResponseData = soapResponseData.split("return")[1].replace(">","").replace("</","");
            Map<String,String> paramMap = new HashMap<String, String>();
            if(!soapResponseData.contains("end")){
                paramMap.put("statu",soapResponseData.split(":")[0]);
                paramMap.put("loginName",soapResponseData.split(":")[1]);
                paramMap.put("taskId",soapResponseData.split(":")[2]);
                return paramMap;
            }else{
               return null;
            }
        }
        else {
            System.out.println("getStatus调用失败！错误码：" + statusCode);
            return null;
        }
    }
    
    /**
     * 开启流程
     * @param createUserId	流程发起人
     * @param comment		发起人意见
     * @param nextUserId	处理人
     * @param flowSign		流程标识
     * @param title			流程标题
     * @return	成功返回流程ID（需保存数据库） 失败返回"error"
     * @throws IOException
     */
    public String  startProcess(String createUserId,String comment,String nextUserId,String dept,String flowSign,String title) throws IOException {
        String soapRequestData =
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:startProcess>\n" +
                        "         <arg0><![CDATA[\n" +
                        "               <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "               <Root>\n" +
                        "               <procDefKey>"+flowSign+"</procDefKey>\n" +//当前传入的流程标识
                        "               <businessTable></businessTable>\n" +
                        "               <businessId></businessId>\n" +
                        "               <createUserId>"+createUserId+"</createUserId>\n" +
                        "               <comment>"+comment+"</comment>\n" +
                        "               <vars>\n" +
                        "                   <title>"+title+"</title>\n" +
                        "                   <nextUserId>"+nextUserId+"</nextUserId>\n" +
                        "                   <dept>"+dept+"</dept>\n" +
                        "               </vars>\n" +
                        "               </Root>\n" +
                        "           ]]></arg0>\n" +
                        "      </web:startProcess>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        
        //System.out.println(soapRequestData);

        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                      "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
        	System.out.println("startProcess调用成功！");
    		String soapResponseData = postMethod.getResponseBodyAsString();
    		return soapResponseData.split("return")[1].replace(">","").replace("</","");
        }
        else {
           System.out.println("startProcess调用失败！错误码：" + statusCode);
           return "error";
       }
    }
    
    /**
     * 流程审核
     * @param taskId		任务ID
     * @param procInsId		流程ID
     * @param comment		意见
     * @param nextUserId 	处理人
     * @param flag			网关 1：通过 0：不通过
     * @return	成功返回"success" 失败返回"error"
     * @throws IOException
     */
    public String  complete(String taskId,String procInsId,String comment,String nextUserId,String flag) throws IOException {
        String soapRequestData =
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:complete>\n" +
                        "         <arg0><![CDATA[\n" +
                        "               <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "               <Root>\n" +
                        "               <taskId>"+taskId+"</taskId>\n" +//当前传入的流程标识
                        "               <procInsId>"+procInsId+"</procInsId>\n" +//流程ID
                        "               <comment>"+comment+"</comment>\n" +
                        "               <vars>\n" +
                        "                   <nextUserId>"+nextUserId+"</nextUserId>\n" +
                        "                   <pass>"+flag+"</pass>\n" +
                        "               </vars>\n" +
                        "               </Root>\n" +
                        "           ]]></arg0>\n" +
                        "      </web:complete>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        
        //System.out.println(soapRequestData);

        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("complete调用成功！");
            String soapResponseData = postMethod.getResponseBodyAsString();
            return soapResponseData.split("return")[1].replace(">","").replace("</","");
        }
        else {
            System.out.println("complete调用失败！错误码：" + statusCode);
            return "error";
        }
    }
    
    /**
     * 开启流程
     * @param createUserId	流程发起人
     * @param comment		发起人意见
     * @param nextUserId	处理人
     * @param dept			单位修志/修志办修志标识  1：单位修志 2：修志办修志
     * @param flowSign		流程标识
     * @param title			流程标题
     * @return	成功返回流程ID（需保存数据库） 失败返回"error"
     * @throws IOException
     */
    public String  startSummaryProcess(String createUserId,String comment,String nextUserId,String dept,String flowSign,String title) throws IOException {
        String soapRequestData =
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:startProcess>\n" +
                        "         <arg0><![CDATA[\n" +
                        "               <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "               <Root>\n" +
                        "               <procDefKey>"+flowSign+"</procDefKey>\n" +//当前传入的流程标识
                        "               <businessTable></businessTable>\n" +
                        "               <businessId></businessId>\n" +
                        "               <createUserId>"+createUserId+"</createUserId>\n" +
                        "               <comment>"+comment+"</comment>\n" +
                        "               <vars>\n" +
                        "                   <title>"+title+"</title>\n" +
                        "                   <nextUserId>"+nextUserId+"</nextUserId>\n" +
                        "                   <dept>"+dept+"</dept>\n" +
                        "               </vars>\n" +
                        "               </Root>\n" +
                        "           ]]></arg0>\n" +
                        "      </web:startProcess>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        
        //System.out.println(soapRequestData);

        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                      "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
        	System.out.println("startProcess调用成功！");
    		String soapResponseData = postMethod.getResponseBodyAsString();
    		return soapResponseData.split("return")[1].replace(">","").replace("</","");
        }
        else {
           System.out.println("startProcess调用失败！错误码：" + statusCode);
           return "error";
       }
    }
    
    /**
     * 流程审核
     * @param taskId		任务ID
     * @param procInsId		流程ID
     * @param comment		意见
     * @param nextUserId 	处理人
     * @param dept			返回修改时判断单位修志/修志办修志标识  1：单位修志 2：修志办修志
     * @param flag			网关 1：通过 0：不通过
     * @return	成功返回"success" 失败返回"error"
     * @throws IOException
     */
    public String  summaryComplete(String taskId,String procInsId,String comment,String nextUserId,String dept,String flag) throws IOException {
        String soapRequestData =
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.act.modules.jeesite.thinkgem.com/\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <web:complete>\n" +
                        "         <arg0><![CDATA[\n" +
                        "               <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "               <Root>\n" +
                        "               <taskId>"+taskId+"</taskId>\n" +//当前传入的流程标识
                        "               <procInsId>"+procInsId+"</procInsId>\n" +//流程ID
                        "               <comment>"+comment+"</comment>\n" +
                        "               <vars>\n" +
                        "                   <nextUserId>"+nextUserId+"</nextUserId>\n" +
                        "                   <dept>"+dept+"</dept>\n" +
                        "                   <pass>"+flag+"</pass>\n" +
                        "               </vars>\n" +
                        "               </Root>\n" +
                        "           ]]></arg0>\n" +
                        "      </web:complete>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
        
        //System.out.println(soapRequestData);

        PostMethod postMethod = new PostMethod(chronConfig.getFlowServiceUrl());

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象，并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("complete调用成功！");
            String soapResponseData = postMethod.getResponseBodyAsString();
            return soapResponseData.split("return")[1].replace(">","").replace("</","");
        }
        else {
            System.out.println("complete调用失败！错误码：" + statusCode);
            return "error";
        }
    }
    
    @SuppressWarnings("unchecked")
	public List<Map<String,String>> getNodes(Element node){
        List<Map<String,String>> listComments=new ArrayList<Map<String, String>>();
        List<Element> listElement=node.elements();//所有一级子节点的list
        for(Element e:listElement){//遍历所有一级子节点
            List<Element> listElement1=e.elements();
            Map<String,String> mapComment = new HashMap<String, String>();
            for(Element e1:listElement1) {
                mapComment.put(e1.getName(), e1.getTextTrim());
            }
            System.out.println(mapComment);
            listComments.add(mapComment);
        }
        return listComments;
    }
}
